package gov.pbc.nn.kjgl.fxq.attachment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.bstek.dorado.core.Configure;
import com.bstek.dorado.uploader.DownloadFile;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileProvider;
import com.bstek.dorado.uploader.annotation.FileResolver;
import com.bstek.dorado.uploader.util.ParameterUtils;
import com.bstek.uflo.designer.utils.EscapeUtils;

@Component
public class MyUploadProcessor {

	private String getDestPath() {
		return System.getProperty("java.io.tmpdir") + File.separator + "upload";
	}

	@SuppressWarnings("unused")
	@FileResolver
	public Map<String, String> process1(UploadFile file, Map<String, Object> parameter) throws Exception {
		String filename = file.getFileName();
		String filesavename = UUID.randomUUID().toString();
		Path path = Paths.get(Configure.getString("FXQ_FILE_UPLOAD_PATH"));
		Files.createDirectories(path);
		path = path.resolve(filesavename);
		File destFile = Files.createFile(path).toFile();
		file.transferTo(destFile);
		Map<String, String> data = new HashMap<String, String>();
		data.put("fileName", filename);
		data.put("path", destFile.getAbsolutePath());
		return data;
	}

	private DownloadFile getDownloadFile(String fileName) throws IOException {
		String name = fileName;
		ParameterUtils.validateParameterCharacters(name);
		URL url = this.getClass().getResource(name);
		InputStream stream = url.openConnection().getInputStream();
		DownloadFile file = new DownloadFile(name, stream);
		if ("UploadAction.pdf".equals(name)) {
			file.setName("UpdateAction用户指南.pdf");
			// 如果文件下载时,中文名称变乱码,可以参考下列代码自定义转码方式,并设置DownloadFile的fileName属性
			// file.setFileName(new
			// String("UpdateAction用户指南.pdf".getBytes("UTF-8"),"iso8859-1"));
		}
		return file;
	}

	@FileProvider
	public DownloadFile download(Map<String, Object> parameter) throws Exception {
		String fileName = EscapeUtils.unescape((String) parameter.get("fileName"));
		String path = EscapeUtils.unescape((String) parameter.get("path"));
		DownloadFile df = new DownloadFile(new File(path));// 返回一个文件对象就可以
		df.setFileName(fileName);
		df.setName(fileName);
		return df;
	}

}
